package com.atguigu.gmall.web.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.FileWriter;
import java.io.IOException;

/**
 * @Author atguigu-mqx
 * @Description TODO
 * @Date 2023/8/25 15:23
 * @Version 1.0
 */
@Controller
public class IndexController {

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private TemplateEngine templateEngine;


    /**
     * 首页分类数据展示
     * @param model
     * @return  ctrl+i  shift+f2 alt+enter ctrl+e ctrl+h
     */
    @GetMapping({"/","index.html"})
    public String index(Model model){
        //  获取分类数据
        Result result = productFeignClient.getBaseCategoryList();
        //  存储数据  model.addAllAttributes(result.getData()); map 中 必须有页面需要渲染的key value map.put("list",data);
        //  model.addAllAttributes(result.getData());
        model.addAttribute("list",result.getData());
        return "index/index";
    }

    /**
     * 创建模版
     * @return
     */

    @GetMapping("createIndex")
    @ResponseBody
    public Result createIndex(){
        //  获取分类数据
        Result result = productFeignClient.getBaseCategoryList();
        //  第一个模版名，第二个模版的内容，第三个数据流
        Context context = new Context();
        context.setVariable("list",result.getData());
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter("D:\\index.html");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        templateEngine.process("index/index.html",context,fileWriter);
        return Result.ok();
    }

}
